package com.letou.ls.ui;

import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.table.JsonUtil;

import com.letou.ls.mode.LotteryDataInfo;
import com.letou.ls.mode.LotteryInfo;
import com.letou.ls.mode.LotteryTypeInfo;
import com.letou.ls.uitl.AppConfigManager;
import com.letou.ls.uitl.AppSettingPreferencesUtils;
import com.letou.ls.uitl.AppShowSettingType;
import com.letou.ls.uitl.Constant;
import com.letou.ls.uitl.DialogUtils;
import com.letou.ls.uitl.Logger;
import com.letou.ls.uitl.LotteryTimeUtils;
import com.letou.ls.uitl.MyUtil;
import com.letou.ls.uitl.PreferencesUtils;
import com.letou.ls.uitl.VersionUpdate;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

@SuppressLint("SimpleDateFormat")
public abstract class BaseActivity extends Activity {
    
    protected int viewWidth;
    protected float density;
    protected GestureDetector mGesture = null;
    protected ProgressDialog mProgressDialog;
    private boolean isFrist = true;
    private FinalHttp fh = null;
    // 定时Timer
    private Timer mTimer = null;
    private List<LotteryInfo> mLotteryList;
    protected String lotteryCode;
    protected int screen_direction_type = 0;
    private String currentLotteryInfoTime = null;
    private LotteryTypeInfo mLotteryTypeInfo;
    private String expirationTime;
    private Date expirationDate;
    private static int number = 0;
    private long exitTime = 0;

    public String mNowTime = "00:00:00";
    public String mCountdownTime = "00:00";
    
    
    public abstract void updateTimeCount(String time);
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            loadData();
            if (number == 0) {
                VersionUpdate.versionLoad(BaseActivity.this);
            }
            number++;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);

        // int height = metric.heightPixels; // 屏幕高度（像素）
        density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
        // int densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240）
        viewWidth = metric.widthPixels;
        mGesture = new GestureDetector(this, new GestureListener());
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("数据加载中请稍候...");
        AppConfigManager.getInstance(BaseActivity.this).initAppsettingConfigs(lotteryCode);
        AppConfigManager.getInstance(BaseActivity.this).initColorsettingConfigs();
    }

    private void obtainLocalTime() {
    	 updateTimeCount("即将开奖");
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                URL url;
                try {
                    url = new URL("http://www.bjtime.cn");
                    URLConnection uc = url.openConnection();
                    uc.connect();
                    long ld = uc.getDate();
                    Date date = new Date(ld);
                    SimpleDateFormat formatter = new SimpleDateFormat("kk:mm:ss");
                    mNowTime = formatter.format(date);
                    Log.e("lb", "现在网络时间:" + mNowTime);
                    startTimer();
                    
                } catch (Exception e) {
                    e.printStackTrace();
                    DateFormat df = new SimpleDateFormat("kk:mm:ss");
                    mNowTime =   df.format(new Date());
                    startTimer();
                    Log.e("lb", "现在本地时间:" + mNowTime);
                }
                
                
            }

			private void startTimer() {
				String[] nowSpit = mNowTime.split(":");
				int nowHours = Integer.valueOf(nowSpit[0]);
				int nowMinute = Integer.valueOf(nowSpit[1]);
				
				if (TextUtils.equals(lotteryCode, Constant.LOTTERY_CODE_04)) {
				    if (nowHours >= 8 && nowMinute >= 5 || nowHours <= 22 && nowMinute <= 35) {
				        mCountdownTime = LotteryTimeUtils.searchFitFivelistTimes(mNowTime);
				        mHandler.removeMessages(3);
				        mHandler.sendEmptyMessageDelayed(3, 1000);
				    }
				    
				} else {
				    if (nowHours >= 8 && nowMinute >= 45 || nowHours <= 22 && nowMinute <= 35) {
				        mCountdownTime = LotteryTimeUtils.searchHappyTenlistTimes(mNowTime);
				        mHandler.removeMessages(3);
				        mHandler.sendEmptyMessageDelayed(3, 1000);
				    }
				}
			}
        }).start();
        
    }
    
    private static SimpleDateFormat formatter;

    public static Date getDateForStr(String text) {
        
        if (formatter == null) {
            formatter = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss");
        }
        Date date = null;
        try {
            date = formatter.parse(text);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return date;
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        Boolean isLoad = true;
        String preferencesLotteryCode =
                PreferencesUtils.getString(this, Constant.PRE_TAG_CURRENT_LTTERY_CODE);
        
        if (!TextUtils.isEmpty(preferencesLotteryCode)) {
            if (AppSettingActivity.sSaveConfig) {
                Intent intent = MyUtil.getIntentById(this, preferencesLotteryCode);

                if (Constant.lotteryTypeInfo != null) {
                    int size = Constant.lotteryTypeInfo.size();
                    for (int index = 0; index < size; index++) {
                        if (preferencesLotteryCode
                                .equals(Constant.lotteryTypeInfo.get(index).getTypeCode())) {
                            Constant.currentLotteryNumber = index;
                            break;
                        }
                    }

                }
                AppSettingActivity.sSaveConfig = false;
                startActivity(intent);
                finish();
                return;
            }

            if (!lotteryCode.equals(preferencesLotteryCode)) {
                isLoad = false;
            } else {
                if (TextUtils.equals(preferencesLotteryCode, Constant.LOTTERY_CODE_04)
                        && screen_direction_type != PreferencesUtils.getInt(this,
                                AppShowSettingType.SCREEN_DIRECTION_TYPE, 1)) {
                    isLoad = false;
                }
            }
            if (!isLoad) {
                Intent intent = MyUtil.getIntentById(this, preferencesLotteryCode);

                if (Constant.lotteryTypeInfo != null) {
                    int size = Constant.lotteryTypeInfo.size();
                    for (int index = 0; index < size; index++) {
                        if (preferencesLotteryCode
                                .equals(Constant.lotteryTypeInfo.get(index).getTypeCode())) {
                            Constant.currentLotteryNumber = index;
                            break;
                        }
                    }

                }
                startActivity(intent);
                finish();
            }
            
        }
        if (isLoad) {
            if (Constant.lotteryTypeInfo != null
                    && Constant.lotteryTypeInfo.size() > Constant.currentLotteryNumber) {
                mLotteryTypeInfo = Constant.lotteryTypeInfo.get(Constant.currentLotteryNumber);
                expirationTime = mLotteryTypeInfo.getExpirationTime();
                if (!TextUtils.isEmpty(expirationTime)) {
                    expirationDate = getDateForStr(expirationTime);
                }
            }
            if (expirationDate != null) {
                Date currentTime = new Date();
                if (currentTime.after(expirationDate)) {
                    showDailog("权限到期！ 你的权限到期时间是: " + expirationTime);
                    return;
                }
            }
            // 01-21 20:53:05.190: E/WindowManager(16250):
            // android.view.WindowLeaked: Activity com.letou.ls.ui.FifFiveActivity
            // has leaked window
            // com.android.internal.policy.impl.PhoneWindow$DecorView{3bdd29e2
            // V.E..... R.....I. 0,0-669,345} that was originally added here

            if (isFrist) {
                if (!this.isFinishing() && !mProgressDialog.isShowing()) {
                    mProgressDialog.show();
                }
                isFrist = false;
                if (!TextUtils.isEmpty(lotteryCode)) {
                    PreferencesUtils.putString(this, Constant.PRE_TAG_CURRENT_LTTERY_CODE,
                            lotteryCode);
                }
            }
            if (mTimer == null) {
                startRefreshTimer();
            }

            // 获取网络时间
            if (TextUtils.equals(mCountdownTime, "00:00")) {
                obtainLocalTime();
            }
        }
        
        
        
    }

    class GestureListener extends SimpleOnGestureListener {
        
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            // TODO Auto-generated method stub
            // Logger.v("TEST", "onDoubleTap");
            return super.onDoubleTap(e);
        }

        @Override
        public boolean onDown(MotionEvent e) {
            // TODO Auto-generated method stub
            // Logger.v("TEST", "onDown");
            return super.onDown(e);
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            // TODO Auto-generated method stub
            Logger.v("TEST",
                    "onScroll:velocityX = " + velocityX + "    " + (e2.getX() - e1.getX()));
            if (e2.getX() - e1.getX() < -viewWidth / 3f) {
                gotoNextActivity(Constant.currentLotteryNumber + 1);
            } else if (e2.getX() - e1.getX() > viewWidth / 3f) {
                gotoNextActivity(Constant.currentLotteryNumber - 1);
            }
            return super.onFling(e1, e2, velocityX, velocityY);
        }

        @Override
        public void onLongPress(MotionEvent e) {
            // TODO Auto-generated method stub
            // Logger.v("TEST", "onLongPress");
            super.onLongPress(e);
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            // TODO Auto-generated method stub
            // Logger.v("TEST", "onScroll:distanceX = " + distanceX + "
            // distanceY = " + distanceY);
            return super.onScroll(e1, e2, distanceX, distanceY);
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            // TODO Auto-generated method stub
            // Logger.v("TEST", "onSingleTapUp");
            return super.onSingleTapUp(e);
        }

    }

    private void gotoNextActivity(int number) {
        if (Constant.lotteryTypeInfo == null || number >= Constant.lotteryTypeInfo.size()
                || number < 0) {
            return;
        }
        String code = Constant.lotteryTypeInfo.get(number).getTypeCode();
        Logger.v("TEST", "code " + code);

        Intent intent = MyUtil.getIntentById(this, code);
        if (intent == null) {
            return;
        }
        Constant.currentLotteryNumber = number;
        startActivity(intent);
        finish();
    }

    /**
     * 开始轮询线程(Timer)
     */
    private void startRefreshTimer() {
        TimerTask mTimerTask = new TimerTask() {
            @Override
            public void run() {
                Message msg = new Message();
                handler.sendMessage(msg);
            }
        };

        mTimer = new Timer();
        // mTimer.schedule(mTimerTask, 1 * 1000, 10 * 1000);
        // mTimer.schedule(mTimerTask, 1 * 1000, 3 * 60 * 1000);
        mTimer.schedule(mTimerTask, 1 * 1000, 20 * 1000);
        // 01-18 13:36:28.625: V/lss(20977):
        // http://119.10.9.19:8080/le-tou/api/version/getVersion?token=B57CAD29EDACE02CDBAF73575D86DC2D

    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        number = 0;
        mProgressDialog.dismiss();
        mHandler.removeMessages(3);
        // saveData();
    }

    private void saveData() {
        
        if (mLotteryList == null || mLotteryList.isEmpty() || TextUtils.isEmpty(lotteryCode)) {
            return;
        }

        String dataStr = JsonUtil.toJson(mLotteryList);
        AppSettingPreferencesUtils.putString(this, lotteryCode, dataStr);

    }

    protected void updateView(List<LotteryInfo> lotteryInfo, String miss, String sum) {
        
    }

    private void loadData() {
        if (expirationDate != null) {
            Date currentTime = new Date();
            if (currentTime.after(expirationDate)) {
                showDailog("权限到期！ 你得权限到期时间是: " + expirationTime);
                return;
            }
        }
        if (TextUtils.isEmpty(lotteryCode)) {
            return;
        }
        fh = new FinalHttp();
        String url;
        // http://119.10.9.19:8080/lottery/api/lottery/getLottery?typeCode=hljklsf&token=1FF114B7BB0478F3B61A5EDAE3B6AF0B
        // url = Constant.URL_SERVER_LOTTERY + "?typeCode=" + lotteryCode +
        // "&token=" + Constant.token + "&order=asc";
        if (TextUtils.isEmpty(currentLotteryInfoTime)) {
            url = Constant.URL_SERVER_LOTTERY + "?typeCode=" + lotteryCode + "&token="
                    + Constant.token;
        } else {
            url = Constant.URL_SERVER_LOTTERY + "?typeCode=" + lotteryCode + "&token="
                    + Constant.token + "&dateline=" + currentLotteryInfoTime;
        }
        Logger.v("lss", "loadData  " + url);
        fh.configTimeout(30000);
        fh.get(url, new AjaxCallBack<String>() {
            @Override
            public void onSuccess(String strJson) {
                LotteryDataInfo lotteryData = JsonUtil.fromJson(strJson, LotteryDataInfo.class);
                mHandler.sendEmptyMessage(0);
                Logger.v("lss", "strJson " + strJson);
                if ("200".equals(lotteryData.getCode())) {
                    
                    if (lotteryData == null || lotteryData.getLotteryInfo() == null) {
                        return;
                    }

                    if (mLotteryList == null) {
                        mLotteryList = new ArrayList<LotteryInfo>();
                    }
                    if (lotteryData.getLotteryInfo().isEmpty()) {
                        return;
                    }
                    ArrayList<LotteryInfo> newlottery = lotteryData.getLotteryInfo();
                    newlottery = getUpdateDate(newlottery);

                    // currentLotteryInfoTime =
                    // lotteryData.getLotteryInfo().get(lotteryData.getLotteryInfo().size()
                    // - 1)
                    // .getDateline();
                    currentLotteryInfoTime = lotteryData.getLotteryInfo().get(0).getDateline();
                    Log.v("lss", "currentLotteryInfoTime  " + currentLotteryInfoTime);
                    currentLotteryInfoTime = MyUtil.changEncoding(currentLotteryInfoTime);
                    mLotteryList.addAll(newlottery);
                    // mLotteryList.addAll(0, newlottery);
                    int size = mLotteryList.size();
                    if (size > 50) {
                        // mLotteryList = mLotteryList.subList(size - 50, size);
                        // mLotteryList = mLotteryList.subList(0, 50);
                        for (int index = 0; index < size - 50; index++) {
                            mLotteryList.remove(0);
                        }

                    }
                    updateView(mLotteryList, lotteryData.getMiss(), lotteryData.getSum());

                } else {
                    // 登陆失败
                    showDailog(MyUtil.getErrByCode(lotteryData.getCode()));
                }
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                mHandler.sendEmptyMessage(1);
            }

        });
    }

    private ArrayList<LotteryInfo> getUpdateDate(ArrayList<LotteryInfo> array) {
        ArrayList<LotteryInfo> newArray = new ArrayList<LotteryInfo>();
        int isize = array.size();
        for (int i = isize - 1; i >= 0; i--) {
            // for (LotteryInfo item : array) {
            // "10,19,13,03,14,09,06,05"
            LotteryInfo item = array.get(i);

            String[] strArray = item.getLotteryNumbers().split(",");
            String newStr = "";
            int size = strArray.length;
            for (int index = 0; index < size; index++) {
                if (index > 0) {
                    newStr = newStr + "," + Integer.valueOf(strArray[index]);
                } else {
                    newStr = "" + Integer.valueOf(strArray[index]);
                }
            }
            item.setLotteryNumbers(newStr);
            newArray.add(item);
        }
        return newArray;

    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if (msg.what == 1) {
                showDailog("网络延时");
            } else if (msg.what == 3) {
                try {
                    updateTimeCount("");
                    // Log.e("lb", "时间倒计时:" + mCountdownTime);
                    String[] spit = mCountdownTime.split(":");
                    int minutes = Integer.valueOf(spit[0]);
                    int second = Integer.valueOf(spit[1]);
                    StringBuffer sb = new StringBuffer();
                    if (second == 0) {
                    	if(minutes!=0){
                    		  minutes--;
                    		  second = 59;
                    	}
                    } else{
                    	 second--;
                    }
                    
                    if(second<0){
                    	second =0;
                    }
                    if(minutes<0){
                    	minutes =0;
                    }
                    if (minutes < 10) {
                        sb.append("0" + minutes + ":");
                    } else {
                        sb.append(minutes + ":");
                    }
                    
                    if (second < 10) {
                        sb.append("0" + second);
                    } else {
                        sb.append(second);
                    }
                    mCountdownTime = sb.toString();
                    if (minutes == 0 && second == 0) {
                        obtainLocalTime();
                    } else {
                    	mHandler.removeMessages(3);
                        mHandler.sendEmptyMessageDelayed(3, 1000);
                    }
                } catch (Exception e) {}


            } else {
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            }
        }
    };

    /**
     * 获得奇数偶数比
     *
     * @param array
     * @return
     */
    protected String getBigSmall(int[] array, int count) {
        
        int big = 0;
        int small = 0;
        for (int number : array) {
            if (number < count) {
                small++;
            } else {
                big++;
            }
        }

        return String.valueOf(big) + ":" + String.valueOf(small);

    }

    /**
     * 获得奇数偶数比
     *
     * @param array
     * @return
     */
    protected String getjiou(int[] array) {
        
        int ji = 0;
        int ou = 0;
        for (int number : array) {
            if (number % 2 == 0) {
                ou++;
            } else {
                ji++;
            }
        }

        return String.valueOf(ji) + ":" + String.valueOf(ou);

    }

    protected void gotoMenuActivity() {
        int currentOrientation = getResources().getConfiguration().orientation;
        Intent intent = new Intent(this, MenuActivity.class);
        intent.putExtra("orientation", currentOrientation);
        startActivityForResult(intent, 1);
    }


    private void showDailog(String message) {
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
        DialogUtils.showDialog(BaseActivity.this, "提示", message);
    }

    // public String mStartTimeStr = "";
    // public String mEndTimeStr = "";
    private static Date mStartTime;
    private static Date mEndTime;
    private static SimpleDateFormat formatter2;

    public void initFirstDateTime(String start, String end) {
        Log.v("TEST", " " + start);
        if (TextUtils.isEmpty(start) || TextUtils.isEmpty(end)) {
            mStartTime = null;
            mEndTime = null;
            return;
        }
        mStartTime = getDateForStr2(start);
        mEndTime = getDateForStr2(end);
        Log.v("TEST", " " + mStartTime);
    }

    public static boolean isFirstData(String data) {
        
        Log.v("TEST", " " + data);
        if (TextUtils.isEmpty(data)) {
            return false;
        }
        if (mStartTime == null || mEndTime == null) {
            return false;
        }
        String[] array = data.split(" ");
        if (array != null && array.length > 1) {
            Date currentTime = getDateForStr2(array[1]);
            Log.v("TEST", " " + array[1] + " " + currentTime);
            if (currentTime.after(mStartTime) && currentTime.before(mEndTime)) {
                return true;
            }
        }
        return false;

    }

    public static Date getDateForStr2(String text) {
        
        if (formatter2 == null) {
            formatter2 = new SimpleDateFormat("kk:mm:ss");
        }
        Date date = null;
        try {
            date = formatter2.parse(text);
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return date;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // if (keyCode == KeyEvent.KEYCODE_BACK
        // && event.getAction() == KeyEvent.ACTION_DOWN) {
        // if ((System.currentTimeMillis() - exitTime) > 2000) {
        // Toast.makeText(getApplicationContext(), "再按一次退出程序",
        // Toast.LENGTH_SHORT).show();
        // exitTime = System.currentTimeMillis();
        // } else {
        // BaseActivity.this.finish();
        // }
        // return true;
        // }
        // return super.onKeyDown(keyCode, event);

        if (keyCode == KeyEvent.KEYCODE_BACK)
            new AlertDialog.Builder(BaseActivity.this).setTitle("系统提示")
                    // 设置对话框标题

                    .setMessage("确定要退出应用")
                    // 设置显示的内容

                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {// 添加确定按钮

                        @Override
                        public void onClick(DialogInterface dialog, int which) {// 确定按钮的响应事件
                            finish();
                        }

                    }).setNegativeButton("返回", new DialogInterface.OnClickListener() {// 添加返回按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {// 响应事件
                            Log.i("alertdialog", " 请保存数据！");
                        }

                    }).show();// 在按键响应事件中显示此对话框
        return false;
    }
}
